﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lekker.Data.Model;

namespace Lekker.Data.Recipes {
    public class RecipeDao : IRecipeDao {

        /*---------------------------------------------------------------------------------------*/
        #region IRecipeDao Members

        public IEnumerable<Recipe> GetRecipes() {
            using (var ctx = new LekkerEntities()) {
                return ctx.Recipes.ToList();
            }
        }

        public IEnumerable<Recipe> GetRecentRecipes() {
            using (var ctx = new LekkerEntities()) {

                var recipes = from recipe in ctx.Recipes
                              orderby recipe.Created descending
                              select recipe;

                return recipes.Take(20).ToList(); ;
            }
        }

        public IEnumerable<GuestMenu> GetRecentGuestMenus() {
            using (var ctx = new LekkerEntities()) {

                var guests = from g in ctx.GuestMenu
                             orderby g.Consumption descending
                             select g;

                var result = guests.Take(5);

                foreach (var item in result) {
                    item.Recipes.Load();
                }

                return result.ToList();
            }
        }

        public Recipe GetRecipe(int id) {
            using (var ctx = new LekkerEntities()) {

                var recipe = ctx.Recipes.Where(r => r.Id == id).First();

                if (recipe != null) {

                    // Load related data
                    recipe.Ingredients.Load();
                    recipe.Tags.Load();
                    recipe.Images.Load();

                    // Detach Object
                    ctx.Detach(recipe);                    
                }

                return recipe;
            }
        }

        public void UpdateRecipe(Recipe recipe) {

            if(recipe == null)
                throw new ArgumentNullException("recipe","Argument is not allowed to be null.");

            using (var ctx = new LekkerEntities()) {
                ctx.AttachUpdated(recipe);
                ctx.SaveChanges();
            }
        }

        #endregion
        /*---------------------------------------------------------------------------------------*/

    }
}
